//
//  LHYPDFAnnotation.m
//  DrawLine
//
//  Created by lhy on 2021/1/28.
//

#import "LHYPDFAnnotation.h"
#import "LHYTextFieldCopyView.h"
#import "LHYImageCopyView.h"

@interface LHYPDFAnnotation ()

@property (nonatomic, strong) UIImage *image;
@property (nonatomic, copy) NSString *text;
@property (nonatomic, assign) CGRect imageframe;
@property (nonatomic, assign) CGRect textFrame;
@property (nonatomic, strong) LHYImageCopyView *imageView;

@end

@implementation LHYPDFAnnotation

- (instancetype)initWithBounds:(CGRect)bounds forType:(PDFAnnotationSubtype)annotationType withProperties:(NSDictionary *)properties {
    
    self = [super initWithBounds:bounds forType:annotationType withProperties:properties];
    if (self) {
        self.backgroundColor = UIColor.clearColor;
        LHYTextFieldCopyView *textField = properties[@"textFieldView"];
        self.imageView = properties[@"imageView"];
        
        self.imageframe = self.imageView.frame;
        self.textFrame = textField.frame;
        self.image = self.imageView.image;
        self.text = textField.text;
    }
    return self;
}

- (void)drawWithBox:(PDFDisplayBox)box inContext:(CGContextRef)context {
    [super drawWithBox:box inContext:context];
    //    打开上下文
    UIGraphicsPushContext(context);
    //    保存上下文
    CGContextSaveGState(context);
    
    CGFloat pageHeight = [self.page boundsForBox:box].size.height;
    
#warning  该方法可解决 在Annotation中绘制翻转问题.    但是需要 annotation.frame = page.frame. 才能正常位置显示
    CGContextTranslateCTM(context, 0, pageHeight);
    CGContextScaleCTM(context, 1.0, -1.0);
    
//    text 已用新方法替换
//    if (self.text.length) {
//        // 对绘制位置进行微调
//        CGFloat x = self.textFrame.origin.x - 4;
//        CGFloat y = self.textFrame.origin.y;
//        [self.text drawInRect:CGRectMake(x, y, self.textFrame.size.width, self.textFrame.size.height) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]}];
//    }
     
    if (self.image) {
        // 对绘制位置进行微调
        CGFloat x = self.imageframe.origin.x - 3;
        CGFloat y = self.imageframe.origin.y - 4 - self.imageView.pageIndex * pageHeight;
        
        [self.image drawInRect:CGRectMake(x, y, self.imageframe.size.width, self.imageframe.size.height)];
    }
    
    //    恢复上下文
    CGContextRestoreGState(context);
    //    推出上下文
    UIGraphicsPopContext();
}

@end
